package com.appleyk.mall.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

import javax.annotation.Resource;

/**
 * <p>越努力，越幸运</p>
 * 资源服务器配置
 * @author appleyk
 * @version V.0.1.1
 * @blob https://blog.csdn.net/appleyk
 * @date created on  9:38 下午 2021/2/18
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    // 资源ID，这个必须和授权服务器中客户端端id对应的资源列表中的内容对应上
    public static final String RESOURCE_ID = "r1";

    @Resource
    private ClientProperties clientProperties;

    // 资源服务令牌解析服务
    @Bean
    public ResourceServerTokenServices tokenServices() {
        // 使用远程服务请求授权服务器来验证客户端发过来的token是否合法，且必须指定token的url、client_id和client_secret
        RemoteTokenServices services = new RemoteTokenServices();
        services.setCheckTokenEndpointUrl(clientProperties.getEndPointUrl());
        services.setClientId(clientProperties.getId());
        services.setClientSecret(clientProperties.getSecret());
        return services;
    }

    // 资源服务器安全配置
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID)
                .tokenServices(tokenServices())
                .stateless(true);
    }

    // 安全机制配置
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/**").access("#oauth2.hasScope('app')")
                .and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
